﻿using System;
using BitBenderGames;
using Extensions;
using UnityEngine;
using Yoozoo.Mars.Got;
using Yoozoo.UI.YGUI;
using Random = UnityEngine.Random;

namespace Yoozoo.Gameplay.City
{
    public class CityNpcDialogueBubble : MonoBehaviour
    {
        public Animation BubbleAnimation;
        
        public RectTransform BubbleRect;
        
        public YText DialogueContent;
        
        /// <summary>
        /// 起始动画名
        /// </summary>
        public string StartAnimationName = "ani_bubble_start";

        /// <summary>
        /// 结束动画名
        /// </summary>
        public string EndAnimationName = "ani_bubble_end";

        /// <summary>
        /// 对话更新时长
        /// </summary>
        public float TalkUpdateDuration = 10f;

        /// <summary>
        /// 对话显示时长
        /// </summary>
        public float TalkShowDuration = 5f;

        private float _Timer = 0;
        private bool _IsHide = false;
        
        void Awake()
        {
            _Timer = TalkShowDuration;
            _IsHide = false;
            TalkUpdateDuration = TalkUpdateDuration + Random.Range(-1, 1);
            TalkShowDuration = TalkShowDuration + Random.Range(-1, 1);
        }

        void Update()
        {
            _Timer += Time.deltaTime;
            if (_Timer >= TalkUpdateDuration)
            {
                _Timer = 0;
                _IsHide = false;
                ShowDialogue();
            }
            else if (_Timer >= TalkShowDuration)
            {
                HideDialogue();
            }    
        }

        void LateUpdate()
        {
            if (CityManager.Instance)
            {
                MobileTouchCamera mobileTouchCamera = CityManager.Instance.mobileTouchCamera;
                if (mobileTouchCamera && mobileTouchCamera.Cam)
                {
                    transform.forward = mobileTouchCamera.Cam.transform.forward;
                }
            }
        }
        
        void ShowDialogue()
        {
            if (!string.IsNullOrEmpty(StartAnimationName))
            {
                BubbleAnimation.Play(StartAnimationName);
            }
            DialogueContent.text = CityRealAiCSharpCallLuaManager.RandomAreaBossDialogueContent();
            BubbleRect.SetWidth(DialogueContent.preferredWidth);
        }

        void HideDialogue()
        {
            if (_IsHide)
            {
                return;
            }

            _IsHide = true;
            if (!string.IsNullOrEmpty(EndAnimationName))
            {
                BubbleAnimation.Play(EndAnimationName);
            }
        }
        
    }

}

